package top.ivansong.cxf.registry.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LocalUntil {
    private static final Log log = LogFactory.getLog(LocalUntil.class);
    
    private static final String[] spacialIPChars = {":", "127.", "169.254.", "255.255.255.255"};
 	
    private LocalUntil(){}
	
	public static String getLocalIP() {
		Set<String> ips = resolveLocalIps();
		for (String e : ips) {
			if (e.startsWith("192.168.") || e.startsWith("10.")) {
				return e;
			}
		}
		
		return ips.isEmpty() ? ":" : ips.toArray(new String[ips.size()])[0];
	}
	
	private static Set<String> resolveLocalIps() {
		Set<InetAddress> addresses = resolveLocalAddresses();
		Set<String> res = new HashSet<>();
		for (InetAddress addr : addresses) {
			res.add(addr.getHostAddress());
		}
		return res;
	}

	/**
	 * 获取本地ip地址，有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
	 */
	private static Set<InetAddress> resolveLocalAddresses() {
		Set<InetAddress> addrs = new HashSet<>();
		Enumeration<NetworkInterface> ns = null;
		try {
			ns = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			log.error("LocalUntil.resolveLocalAddresses error.", e);
		}
		while (ns != null && ns.hasMoreElements()) {
			NetworkInterface n = ns.nextElement();
			Enumeration<InetAddress> is = n.getInetAddresses();
			while (is.hasMoreElements()) {
				InetAddress i = is.nextElement();
				if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
						&& !isSpecialIp(i.getHostAddress())){
					addrs.add(i);
				}
			}
		}
		return addrs;
	}

	private static boolean isSpecialIp(String ip) {
	    for (String string : spacialIPChars) {
			if (ip.contains(string)) {
				return true;
			}
		}
		return false;
	}
}
